<template>
  <div class="stock-inout-container">
    <!-- 页面标题 -->
    <div class="header">
      <h2>模具出入库管理系统</h2>
      <div class="info-bar">
        <span>[空闲中]</span>
        <span>登录人：{{ loginName }}</span>
        <span>{{ currentTime }}</span>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-form :inline="true" size="medium" label-width="80px" class="search-form">
        <el-form-item label="图号">
          <el-input v-model="query.form.drawingNo" placeholder="请输入图号" style="width: 240px;"
            @focus="handleInputFocus('drawingNo')" ref="drawingNoRef" />
        </el-form-item>

        <el-form-item label="模具名">
          <el-input v-model="query.form.name" placeholder="请输入模具名" style="width: 200px;"
            @focus="handleInputFocus('code')" ref="codeInputRef" />
        </el-form-item>

        <el-form-item style="margin-left: auto;">
          <el-button type="primary" @click="handleSearch" :loading="searchLoading">查询</el-button>
          <el-button type="danger" @click="handleLogout" :loading="logoutLoading">退出</el-button>
          <el-button type="success" @click="handleMove" :loading="moveLoading">搬入</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table :data="tableData" border style="width: 100%" :max-height="calcMaxHeight()" row-key="id"
        :tree-props="{ children: 'accounts', hasChildren: 'hasAccounts' }" v-loading="tableLoading">
        <el-table-column type="expand" width="60">
          <template #default="{ row }">
            <div class="sub-table-container" v-if="row.accounts?.length">
              <el-table :data="row.accounts" border size="small" class="sub-table">
                <el-table-column prop="inventoryStatus" label="库存状态" width="100" align="center">
                  <template #default="{ row: account }">
                    <el-tag :type="account.inventoryStatus === '1' ? 'success' : 'danger'">
                      {{ account.inventoryStatus === '1' ? '在库' : '出库' }}
                    </el-tag>
                  </template>
                </el-table-column>

                <el-table-column prop="name" label="模具名" min-width="200" align="center" />
                <el-table-column prop="code" label="模具编码" min-width="200" align="center" />
                <el-table-column prop="devName" label="绑定设备" min-width="150" align="center">
                  <template #default="{ row: account }">
                    <span>{{ [account.devName, account.devCode, account.devPosition].filter(Boolean).join(' - ')
                      }}</span>
                  </template>
                </el-table-column>

                <el-table-column prop="customer" label="当前储位" min-width="120" align="center">
                  <template #default="{ row: account }">
                    <span>{{ `${account.warehouseName || ''}${account.storageName ? '/' + account.storageName : ''}`
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="upkeepCategory" label="保养类型" min-width="120" align="center" />
                <el-table-column label="操作" width="200" align="center" fixed="right">
                  <template #default="{ row: account }">
                    <template v-if="account.inventoryStatus === '1'">
                      <el-button size="small" type="danger" @click="handleOut(account)"
                        :loading="account.loading">出库</el-button>
                    </template>
                    <el-button v-else size="small" type="primary" @click="handleIn(account)"
                      :loading="account.loading">入库</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else class="no-data">暂无模具台账数据</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="库存数量" width="120" align="center">
          <template #default="{ row }">
            <span>{{ getStatusText(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="drawingNo" label="图号" min-width="200" show-overflow-tooltip align="center" />
        <el-table-column prop="customer" label="默认设备" min-width="120" align="center">
          <template #default="{ row }">
            <span>{{ [row.devName, row.devCode, row.devPosition].filter(Boolean).join(' - ') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="customer" label="默认储位" min-width="120" align="center">
          <template #default="{ row }">
            <span>{{ `${row.warehouseName || ''}${row.storageName ? '/' + row.storageName : ''}` }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="customer" label="客户名" min-width="120" align="center" />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="danger" @click="handleBatchOut(row)"
              :loading="row.batchOutLoading">出库</el-button>
            <el-button size="small" type="primary" @click="handleBatchIn(row)"
              :loading="row.batchInLoading">入库</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination :current-page="currentPage" :page-sizes="[15, 30, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" background :disabled="tableLoading" />
    </div>

    <!-- 登录弹窗 -->
    <el-dialog v-model="loginVisible" title="员工登录" width="400px" center :close-on-click-modal="false"
      :show-close="false" @opened="onDialogOpen">
      <el-form :model="loginForm" label-width="80px" size="medium">
        <el-form-item label="厂区">
          <el-select v-model="loginForm.tenantId" placeholder="请选择厂区">
            <el-option label="六厂" value="122" />
            <el-option label="测试" value="121" />
          </el-select>
        </el-form-item>
        <el-form-item label="卡号">
          <el-input v-model="loginForm.cardNumber" placeholder="请扫描员工卡号" value="19817336145" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handleLogin" :loading="loginLoading">登录</el-button>
      </template>
    </el-dialog>

    <VirtualKeyboard ref="keyboardRef" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { StockIoApi } from '@/api/mold/workstation/stockio'
import VirtualKeyboard from './keyboard.vue'
import { setCookie, getCookie, removeCookie } from '@/utils/auth'
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus'

// Refs
const keyboardRef = ref(null)
const codeInputRef = ref(null)
const drawingNoRef = ref(null)
const loginVisible = ref(true)
const loginName = ref('')
const currentTime = ref('')
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(0)
const activeInputType = ref('')

// 加载状态 - 移除了全局加载遮罩
const loginLoading = ref(false)
const searchLoading = ref(false)
const logoutLoading = ref(false)
const moveLoading = ref(false)
const tableLoading = ref(false)

let searchTimer = null

// Reactive data
const loginForm = reactive({ tenantId: '', cardNumber: '19817336145' })
const query = reactive({ form: { drawingNo: '', name: '', inventoryStatus: '' } })

// Computed methods
const checkLoginStatus = () => loginForm.tenantId && loginName.value
const calcMaxHeight = () => window.innerHeight - 320

// Methods
const updateTime = () => currentTime.value = new Date().toLocaleString()
updateTime()
setInterval(updateTime, 1000)

const handleInputFocus = (type) => {
  activeInputType.value = type
  nextTick(() => {
    let inputElement = null
    if (type === 'code') inputElement = codeInputRef.value?.$el?.querySelector('input')
    else if (type === 'drawingNo') inputElement = drawingNoRef.value?.$el?.querySelector('input')

    if (inputElement && keyboardRef.value) {
      setTimeout(() => keyboardRef.value.openKeyboard(inputElement), 10)
    }
  })
}

const handleSearch = async () => {
  searchLoading.value = true
  currentPage.value = 1
  await fetchTableData()
  searchLoading.value = false
}

const handleLogout = () => {
  logoutLoading.value = true
  // 模拟退出操作
  setTimeout(() => {
    loginName.value = ''
    loginForm.tenantId = ''
    loginForm.cardNumber = ''
    removeCookie('card_number_stock')
    removeCookie('tenant_id_stock')
    removeCookie('user_id_stock')
    loginVisible.value = true
    logoutLoading.value = false
    ElMessage.success('退出成功')
  }, 500)
}

const handleMove = () => {
  if (!checkLoginStatus()) {
    ElMessage.warning('请先登录')
    loginVisible.value = true
    return
  }

  moveLoading.value = true
  // 模拟搬入操作
  setTimeout(() => {
    moveLoading.value = false
    ElMessage.success('搬入操作成功')
  }, 1000)
}

const handleStatusChange = async (row, status, actionName) => {
  if (!checkLoginStatus()) {
    ElMessage.warning('请先登录')
    loginVisible.value = true
    return
  }

  // 设置单个操作的加载状态
  row.loading = true

  try {
    const input = await ElMessageBox.prompt(`请输入${actionName}备注`, `${actionName}备注`)
    if (!input.value) {
      ElMessage.warning('备注不能为空')
      return
    }

    const userId = getCookie('user_id_stock')
    const response = await StockIoApi.modStatus(
      { account_id: row.id, status, data: input.value, user_id: userId },
      { 'Tenant-Id': loginForm.tenantId }
    )

    // 修改判断逻辑，检查 allowed 字段
    if (response && response.allowed) {
      ElMessage.success(`${actionName}成功`)
      await fetchTableData()
    } else {
      // 显示服务器返回的具体错误信息
      const errorMessage = response?.message || `${actionName}失败，请重试`
      ElMessage.error(errorMessage)
    }
  } catch (error) {
    if (error !== 'cancel') { // 忽略取消操作的错误
      ElMessage.error('网络错误，请重试')
    }
  } finally {
    row.loading = false
  }
}

const handleOut = (row) => handleStatusChange(row, '0', '出库')
const handleIn = (row) => handleStatusChange(row, '1', '入库')

// 修改 handleBatchOperation 函数，使用行级别的加载状态
const handleBatchOperation = async (row, status, actionName, filterStatus) => {
  if (!checkLoginStatus()) {
    ElMessage.warning('请先登录')
    loginVisible.value = true
    return
  }

  if (!row.accounts || row.accounts.length === 0) {
    ElMessage.warning('该图号下没有模具台账')
    return
  }

  // 设置批量操作的加载状态
  if (status === 0) {
    row.batchOutLoading = true
  } else {
    row.batchInLoading = true
  }

  try {
    const input = await ElMessageBox.prompt(`请输入批量${actionName}备注`, `批量${actionName}备注`)
    if (!input.value) {
      ElMessage.warning('备注不能为空')
      return
    }

    const userId = parseInt(getCookie('user_id_stock'))
    // 根据状态过滤模具
    const accountIds = row.accounts
      .filter(account => account.inventoryStatus === filterStatus)
      .map(account => account.id)

    if (accountIds.length === 0) {
      ElMessage.warning(`没有符合条件的模具可以${actionName}`)
      return
    }

    // 调用批量接口 - 修正参数格式
    const response = await StockIoApi.modMutiStatus(
      {
        userId: userId, // 使用驼峰命名
        accountIds: accountIds, // 使用驼峰命名
        status: parseInt(status), // 转换为数字类型
        data: input.value
      },
      { 'Tenant-Id': loginForm.tenantId }
    )

    // 修改响应处理逻辑
    if (response && Array.isArray(response)) {
      const allSuccess = response.every(item => item.allowed)
      if (allSuccess) {
        ElMessage.success(`批量${actionName}成功`)
        await fetchTableData()
      } else {
        // 找出失败的原因
        const failedResults = response.filter(item => !item.allowed)
        const errorMessage = failedResults.map(item => item.message).join('；')
        ElMessage.error(`部分操作失败：${errorMessage}`)
      }
    } else {
      ElMessage.error(`批量${actionName}失败，请重试`)
    }
  } catch (error) {
    if (error !== 'cancel') { // 忽略取消操作的错误
      console.error('批量操作错误:', error)
      ElMessage.error(`批量${actionName}失败，请重试`)
    }
  } finally {
    // 重置批量操作的加载状态
    if (status === 0) {
      row.batchOutLoading = false
    } else {
      row.batchInLoading = false
    }
  }
}

// 修改 handleBatchOut 函数，添加确认弹窗
const handleBatchOut = async (row) => {
  if (!checkLoginStatus()) {
    ElMessage.warning('请先登录')
    loginVisible.value = true
    return
  }

  try {
    await ElMessageBox.confirm(
      `图号"${row.drawingNo}"下的模具将全部进行出库，是否继续？`,
      '出库确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await handleBatchOperation(row, 0, '出库', '1')
  } catch {
    // 用户取消操作
    ElMessage.info('已取消出库操作')
  }
}

// 修改 handleBatchIn 函数，添加确认弹窗
const handleBatchIn = async (row) => {
  if (!checkLoginStatus()) {
    ElMessage.warning('请先登录')
    loginVisible.value = true
    return
  }

  try {
    await ElMessageBox.confirm(
      `图号"${row.drawingNo}"下的模具将全部进行入库，是否继续？`,
      '入库确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await handleBatchOperation(row, 1, '入库', '0')
  } catch {
    // 用户取消操作
    ElMessage.info('已取消入库操作')
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTableData()
}

const handleLogin = async () => {
  if (!loginForm.tenantId || !loginForm.cardNumber) {
    ElMessage.error('请填写厂区和卡号')
    return
  }

  loginLoading.value = true

  try {
    const response = await StockIoApi.login({ card_number: loginForm.cardNumber, tenant_id: loginForm.tenantId })
    if (response) {
      loginName.value = response.nickname
      loginVisible.value = false
      ElMessage.success('登录成功')

      setCookie('card_number_stock', loginForm.cardNumber)
      setCookie('tenant_id_stock', loginForm.tenantId)
      setCookie('user_id_stock', response.id)

      await fetchTableData()
    } else {
      ElMessage.error('登录失败：未找到该用户')
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试')
  } finally {
    loginLoading.value = false
  }
}

const fetchTableData = async () => {
  if (!loginForm.tenantId) {
    ElMessage.error('请先登录')
    loginVisible.value = true
    return
  }

  tableLoading.value = true

  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      ...query.form
    }

    // 清理空参数
    Object.keys(params).forEach(key => !params[key] && delete params[key])

    const response = await StockIoApi.getPage(params, { 'Tenant-Id': loginForm.tenantId })

    const processedData = response.list.map(item => ({
      ...item,
      accounts: item.accounts?.map(account => ({
        ...account,
        status: account.inventoryStatus === '1' ? '在库' : account.inventoryStatus === '0' ? '出库' : '未知',
        loading: false // 为每个台账项添加加载状态
      })) || [],
      hasAccounts: item.accounts?.length > 0,
      batchOutLoading: false, // 批量出库加载状态
      batchInLoading: false   // 批量入库加载状态
    }))

    tableData.value = processedData
    total.value = response.total
  } catch (error) {
    ElMessage.error('网络错误，请重试')
  } finally {
    tableLoading.value = false
  }
}

const onDialogOpen = () => {
  loginForm.tenantId = ''
  loginForm.cardNumber = '19817336145'
}

// Lifecycle
onMounted(() => {
  const savedCardNumber = getCookie('card_number_stock')
  const savedTenantId = getCookie('tenant_id_stock')

  if (savedCardNumber && savedTenantId) {
    loginForm.cardNumber = savedCardNumber
    loginForm.tenantId = savedTenantId
    fetchTableData()
  } else {
    loginVisible.value = true
  }
})

onUnmounted(() => {
  if (searchTimer) clearTimeout(searchTimer)
})

// Watchers
watch(loginName, (newVal) => !newVal && (loginVisible.value = true))
watch(() => query.form.name, (newVal) => {
  if (newVal?.trim()) {
    if (searchTimer) clearTimeout(searchTimer)
    searchTimer = setTimeout(handleSearch, 100)
  }
})

const getStatusText = (row) => {
  if (!row.accounts || row.accounts.length === 0) {
    return '0/0';
  }

  const totalCount = row.accounts.length;
  const inStockCount = row.accounts.filter(account => account.inventoryStatus === '1').length;

  return `${inStockCount}/${totalCount}`;
}
</script>

<style scoped>
.stock-inout-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  font-size: 14px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.info-bar {
  color: #666;
  font-size: 14px;
}

.info-bar span {
  margin-left: 15px;
}

.search-bar {
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: auto;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-top: 10px;
}

.sub-table-container {
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  margin: 5px 0;
}

.sub-table {
  width: 100%;
  background: white;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #909399;
  font-size: 14px;
}

.sub-table-cell {
  display: block;
  padding-left: 60px;
  /* 与图号列对齐 */
}

/* 全局样式优化 */
:deep(.el-table) {
  color: #333;
  /* 加深字体颜色 */
  font-weight: 500;
}

:deep(.el-table .el-table__row) {
  color: #333;
}

:deep(.el-table .el-table__cell) {
  color: #333;
}

:deep(.el-button) {
  font-size: 14px;
  padding: 8px 16px;
  margin-right: 5px;
}

:deep(.el-button:last-child) {
  margin-right: 0;
}

:deep(.el-pagination) {
  font-size: 14px;
}

:deep(.el-pagination .el-pager li) {
  min-width: 35px;
  font-size: 14px;
}

:deep(.el-input__inner) {
  font-size: 16px;
  height: 40px;
}

:deep(.el-button--success) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--warning) {
  background-color: #e6a23c;
  border-color: #e6a23c;
}

:deep(.el-button--primary) {
  background-color: #67c23a;
  border-color: #67c23a;
}

:deep(.el-table__expand-icon) {
  color: #409eff;
}

:deep(.el-table__expand-icon--expanded) {
  transform: rotate(90deg);
}

/* 加载状态时禁用分页 */
:deep(.el-pagination.is-disabled) {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>